package com.cs.rabbittest.demo.routing;

import com.cs.rabbittest.demo.BaseFactory;
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author james
 */
public class Consumer03_rouring__email {

    // 队列名称
    private static final String QUEUE_INFORM_EMAIL = "queue_inform_email";
    // sms队列名称
    private static final String QUEUE_INFORM_SMS = "queue_inform_sms";
    // 交换机名称
    private static final String EXCHANGE_ROUTING_INFORM = "exchange_routing_inform";

    public static void main(String[] args) {
        ConnectionFactory factory = BaseFactory.getConnection();

        try {
            Connection connection = factory.newConnection();
            // 创建与交换机的通道, 每个通道代表一个会话
            Channel channel = connection.createChannel();
            // 声明交换机
            channel.exchangeDeclare(EXCHANGE_ROUTING_INFORM, BuiltinExchangeType.DIRECT);

            // 声明队列
            channel.queueDeclare(QUEUE_INFORM_EMAIL, true, false, false, null);
            // 队列和消费者绑定
            /**
             * 1.队列名称
             * 2.交换机名称
             * 3.路由key
             */
            channel.queueBind(QUEUE_INFORM_EMAIL, EXCHANGE_ROUTING_INFORM, QUEUE_INFORM_EMAIL);
            // 声明消费者
            DefaultConsumer consumer = new DefaultConsumer(channel) {
                /**
                 * No-op implementation of {@link Consumer#handleDelivery}.
                 *
                 * @param consumerTag
                 * @param envelope
                 * @param properties
                 * @param body
                 */
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.printf("Email 消费者收到信息%s\n",message);
                    // 手动应答
                    channel.basicAck(envelope.getDeliveryTag(), false);
                }
            };
            channel.basicConsume(QUEUE_INFORM_EMAIL, false,consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }
    }
}
